package com.rabbiter.market.service.shoppingcart.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbiter.market.common.redis.service.RedisTemplateService;
import com.rabbiter.market.domain.goods.goods_info.Goods;
import com.rabbiter.market.domain.personnel.employee.Employee;
import com.rabbiter.market.domain.shoppingcart.ShoppingCart;
import com.rabbiter.market.mapper.shoppingcart.ShoppingCartMapper;
import com.rabbiter.market.qo.shoppingcaet.ShoppingCartQo;
import com.rabbiter.market.service.goods_management.goods.IGoodsService;
import com.rabbiter.market.service.shoppingcart.ShoppingCartService;
import com.rabbiter.market.vo.shoppingcart.ShoppingCartVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: longxianghang
 * @date: 2025/3/20 17:33
 * @description:
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    @Resource
    private RedisTemplateService redisTemplateService;

    @Resource
    private IGoodsService goodsService;


    @Override
    public Boolean addGoodsToCart(ShoppingCart shoppingCart, String token) {
        String str = redisTemplateService.getCacheObject(token);
        Employee employee = JSONObject.parseObject(str, Employee.class);
        shoppingCart.setUserId(employee.getId());

        // 查询当前商品是否已加入购物车，如果有，则数量+1，如果没有，则新增
        Long count = baseMapper.selectCount(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, employee.getId())
                .eq(ShoppingCart::getProductId, shoppingCart.getProductId()));
        if (count > 0) {
            ShoppingCart cart = baseMapper.selectOne(new LambdaQueryWrapper<ShoppingCart>()
                    .eq(ShoppingCart::getUserId, employee.getId())
                    .eq(ShoppingCart::getProductId, shoppingCart.getProductId()));
            cart.setNum(cart.getNum() + 1);
            return baseMapper.updateById(cart) > 0;
        }

        return baseMapper.insert(shoppingCart) > 0;
    }

    @Override
    public List<ShoppingCartVo> getCartList(ShoppingCartQo qo, String token) {
        String str = redisTemplateService.getCacheObject(token);
        Employee employee = JSONObject.parseObject(str, Employee.class);
        LambdaQueryWrapper<ShoppingCart> wrapper =  new LambdaQueryWrapper<ShoppingCart>();
        wrapper.eq(ShoppingCart::getUserId, employee.getId());
        if(qo.getCartIds() != null && !qo.getCartIds().isEmpty()) {
            wrapper.in(ShoppingCart::getId, qo.getCartIds());
        }
        List<ShoppingCart> shoppingCartList = baseMapper.selectList(wrapper);

        if(shoppingCartList.isEmpty()) {
            return new ArrayList<>();
        }

        List<Long> goodsIds = shoppingCartList.stream().map(ShoppingCart::getProductId).collect(Collectors.toList());

        // 映射成Map
        List<Goods> goodsList = goodsService.listByIds(goodsIds);
        Map<Long, Goods> goodsMap = goodsList.stream().collect(Collectors.toMap(Goods::getId, id -> id));

        List<ShoppingCartVo> shoppingCartVoList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            ShoppingCartVo vo = new ShoppingCartVo();
            Goods goods = goodsMap.get(cart.getProductId());
            vo.setId(cart.getId());
            vo.setNum(cart.getNum());
            vo.setGoodsId(cart.getProductId());
            vo.setName(goods.getName());
            vo.setInfo(goods.getInfo());
            vo.setCoverUrl(goods.getCoverUrl());
            vo.setPurchashPrice(goods.getPurchashPrice());
            vo.setSellPrice(goods.getSellPrice());
            vo.setResidueNum(goods.getResidueNum());
            vo.setResidueNum(goods.getResidueNum());
            vo.setState(goods.getState());

            shoppingCartVoList.add(vo);
        }
        return shoppingCartVoList;
    }

    @Override
    public Object updateCartNum(ShoppingCart shoppingCart, String token) {
        String str = redisTemplateService.getCacheObject(token);
        Employee employee = JSONObject.parseObject(str, Employee.class);
        ShoppingCart cart = baseMapper.selectOne(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getUserId, employee.getId())
                .eq(ShoppingCart::getProductId, shoppingCart.getProductId()));
        cart.setNum(shoppingCart.getNum());
        return baseMapper.updateById(cart) > 0;
    }

    @Override
    public Boolean deleteCartGoods(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
